package com.hontech.desktoppastacooker.utils

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Environment
import android.provider.Settings
import androidx.core.content.ContextCompat.startActivity
import com.hontech.desktoppastacooker.app.AppContext
import com.hontech.desktoppastacooker.ui.activity.BaseActivity
import java.io.PrintWriter


const val AppId = "com.hontech.desktoppastacooker"

const val TMP_DIR = "/data/local/tmp"

fun dimenById(id: Int): Int {
    return AppContext.resources.getDimension(id).toInt()
}

val PackageName = AppContext.packageName
val Version = AppContext.packageManager.getPackageInfo(PackageName, 0).versionName


fun installApk2(path: String): Boolean {
    log("开始安装:$path")
    val prcess = Runtime.getRuntime().exec("su")
    val pw = PrintWriter(prcess.outputStream)
    pw.println("pm install -r -t $path")
    pw.flush()
    pw.close()
    val v = prcess.waitFor()
    log("安装返回值:$v")
    return v == 0
}

fun checkInstallPermission(): Boolean {
    if (!checkAndGrantPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
        return false
    }
    return checkAndGrantPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
}

suspend fun writePermissionCheck() {

    val ret = PromiseTask { checkInstallPermission() }.await(NetTask)
    if (!ret) {
        BaseActivity.INSTANCE.requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
        BaseActivity.INSTANCE.requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    }

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
        if (!Environment.isExternalStorageManager()) {
            val intent = Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            AppContext.startActivity(intent)
            throw IllegalStateException("请授权")
        }
    }
}

fun grantPermission(name: String): Boolean {
    log("获取权限:$name")
    val runtime = Runtime.getRuntime()
        .exec("su")
    val pw = PrintWriter(runtime.outputStream)
    pw.write("pm grant $AppId $name")
    pw.flush()
    pw.close()
    val v = runtime.waitFor()
    return v == 0
}

fun checkAndGrantPermission(name: String): Boolean {
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.M) {
        return true
    }
    val ret = AppContext.checkSelfPermission(name)
    if (ret == PackageManager.PERMISSION_GRANTED) {
        log("已经授权:$name")
        return true
    }
    return try {
        grantPermission(name)
    } catch (e: Exception) {
        e.printStackTrace()
        false
    }
}

